﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using FJASPX.Framwork.Dao;
using log4net;
using NHibernate.Context;
using NHibernate;

namespace FJASPX.Framwork.Web
{
    public class NHSessionModule : IHttpModule
    {
        private static readonly ILog log = LogManager.GetLogger(typeof(NHSessionModule));
        /// <summary>
        /// Default constructor.
        /// </summary>
        public NHSessionModule()
        {
        }
        public void Init(HttpApplication context)
        {
            context.BeginRequest += new EventHandler(Context_BeginRequest);
            context.EndRequest += new EventHandler(Context_EndRequest);
        }
        public void Dispose()
        {
            // Nothing here    
        }

        private void Context_BeginRequest(object sender, EventArgs e)
        {
            // Create the repository for Core objects and add it to the current HttpContext.
            Repository repository = new Repository(true);
            HttpContext.Current.Items.Add("Repository", repository);
        }

        private void Context_EndRequest(object sender, EventArgs e)
        {
            // Close the NHibernate session.
            if (HttpContext.Current.Items["Repository"] != null)
            {
                Repository cr = (Repository)HttpContext.Current.Items["Repository"];
                cr.CloseSession();
            }
        }
        public void ApplicationBeginRequest(object sender, EventArgs e)
        {
            CurrentSessionContext.Bind(NHSessionFactory.Instance.GetCurrentSession());
        }

        public void ApplicationEndRequest(object sender, EventArgs e)
        {
            ISession currentSession = CurrentSessionContext.Unbind(
                NHSessionFactory.factory);
            currentSession.Close();
            currentSession.Dispose();
        }


    }
}
